<template>
  <div class="footer-content">
    <div class="item" @click="prevStepOperate()">
      <img class="item-icon" src="@/assets/images/ic_btn_undo_enable.png" alt="">
      <span class="item-label">撤销</span>
    </div>
    <div class="item" @click="nextStepOperate()">
      <img class="item-icon" src="@/assets/images/ic_btn_reundo_enable.png" alt="">
      <span class="item-label">还原</span>
    </div>
    <template v-if="queryParams && queryParams.design_type == 1">
      <div class="item">
        <div @click="handlelayer">
          <img class="item-icon" src="@/assets/images/ic_btn_layer_enable.png" alt="">
          <span class="item-label">图层</span>
        </div>
        <div v-show="layerShow" class="layer-container">
          <div class="layer-content">
            <div class="layer-item" @click="itemBringToFront">
              <img class="layer-item-icon" src="@/assets/images/ic_tc_zd.png" alt="">
              <span class="item-label-text">置顶</span>
            </div>
            <div class="layer-item" @click="itemBringForward">
              <img class="layer-item-icon" src="@/assets/images/ic_tc_syc.png" alt="">
              <span class="item-label-text">上一层</span>
            </div>
            <div class="layer-item" @click="itemSendBackwards">
              <img class="layer-item-icon" src="@/assets/images/ic_tc_xyc.png" alt="">
              <span class="item-label-text">下一层</span>
            </div>
            <div class="layer-item" @click="itemSendToBack">
              <img class="layer-item-icon" src="@/assets/images/ic_tc_zdb.png" alt="">
              <span class="item-label-text">置底</span>
            </div>
          </div>
        </div>
      </div>
      <div class="item" @click="handleAddGroupModel">
        <div class="save-btn">成组</div>
      </div>
      <div class="item" @click="handleReloadModel">
        <div class="save-btn">重置</div>
      </div>
    </template>
    <template v-else>
      <!-- v-if="!isIos" -->
      <div v-if="queryParams.isAuthor === '0'" class="save-btn-container">
        <van-button type="info" size="small" @click="handleImagePreview" block color="linear-gradient(to right, #8773f9, #1989fa)">
          <span class="save-text">立即制作</span>
        </van-button>
      </div>
      <div v-else-if="queryParams.isAuthor === '1'" class="save-btn-container">
        <van-button type="info" size="small" @click="handleImagePreview" block color="linear-gradient(to right, #8773f9, #1989fa)">
          <span class="save-text">立即制作</span>
        </van-button>
      </div>
      <!-- <div v-else class="save-btn-container ios-btn-tip">
        <van-button type="info" size="small" @click="handleIosTip" block color="linear-gradient(to right, #8773f9, #1989fa)">
          <span class="save-text">苹果系统暂不支持</span>
        </van-button>
      </div> -->
    </template>
    <!-- 预览图片 -->
    <van-popup v-model="showImage" round :style="{ maxHeight: '80%', width: '80%' }">
      <div class="image-container">
        <div class="image-content">
          <van-image
            width="100%"
            fit="contain"
            :src="imageBase64"
            style="float: left;"
          />
        </div>
      </div>
    </van-popup>
    <!-- 编辑完成 -->
    <van-popup v-model="showSaveImage" round :style="{ maxHeight: '90%', width: '90%' }">
      <div class="image-container">
        <div class="preview-title">请预览您的模板制作效果</div>
        <div class="preview-image-container">
          <van-image
            width="100%"
            height="380px"
            fit="contain"
            :src="imageBase64"
            style="float: left;"
          />
          <div class="water-container"></div>
        </div>
        <div class="save-tip">确认无误后请点下方无水印制作可制作和保存高清无水印作品</div>
        <div class="preview-btn-container">
          <van-button type="default" block style="margin-right: 12px;" @click="showSaveImage = false">返回修改</van-button>
          <van-button type="info" block color="linear-gradient(to right, #8773f9, #1989fa)" @click="handleMakePic">无水印制作</van-button>
        </div>
      </div>
    </van-popup>
    <!-- 设置谐音字 -->
    <van-popup v-model="showXieYinSet" round :style="{ maxHeight: '80%', width: '80%' }">
      <div class="image-container">
        <van-field label-width="4em" v-model="xieYinForm.xieYinText" label="谐音字" :border="true" placeholder="谐音字，必须文字匹配上" />
        <van-field label-width="4em" v-model="xieYinForm.xieYinColor" label="谐音颜色" :border="true" placeholder="请输入谐音字颜色" />
        <div class="set-direction">
          <div class="label">文字方向</div>
          <van-radio-group v-model="xieYinForm.textDirection" direction="horizontal">
            <van-radio name="horizontal">横向</van-radio>
            <van-radio name="vertical">竖向</van-radio>
          </van-radio-group>
        </div>
        <van-button type="info" round block @click="handleSetxieYinColor">提交</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { ImagePreview } from 'vant';
import { uploadImgByBase64, createWallpaperTemplate, createPicSynthesisLog } from '@/utils/api'
export default {
  components: {
    [ImagePreview.Component.name]: ImagePreview.Component,
  },
  data() {
    return {
      showXieYinSet: false,
      layerShow: false,
      moreShow: false,
      currentSelectionElement: null,
      imageBase64: '',
      showImage: false,
      showSaveImage: false,
      title: '',
      templateDetail: null,
      queryParams: null,
      isIos: false,
      xieYinForm: {
        xieYinText: '',
        xieYinColor: '',
        textDirection: 'horizontal', // 方向 horizontal 横 vertical 竖
      }
    }
  },
  watch: {
    '$store.state.design.currentSelectionElement': {
      immediate: true,
      handler(val, oldVal) {
        if (val) {
          this.currentSelectionElement = val;
          this.layerShow = false;
          this.moreShow = false;
          this.xieYinForm.xieYinText = val.xieYinText;
          this.xieYinForm.xieYinColor = val.xieYinColor;
          this.xieYinForm.textDirection = val.textDirection || 'horizontal';
        } else {
          this.currentSelectionElement = null;
          this.layerShow = false;
          this.moreShow = false;
        }
      } 
    },
    '$store.state.user.queryParams': {
      immediate: true,
      handler(val) {
        if (val) {
          this.queryParams = val;
        }
      }
    }
  },

  created() {
    let userAgent = navigator.userAgent;
    let isiOS = !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    this.isIos = isiOS;
  },

  methods: {

    // 确定设置谐音
    handleSetxieYinColor() {
      this.handAccountCanvas.updateTextBox({
        type: 'xieYin',
        content: this.xieYinForm
      }).then(() => {
        this.showXieYinSet = false;
      })
    },

    // 设置谐音
    handleXieYin() {
      this.showXieYinSet = true;
    },

    // 无水印制作
    handleMakePic2() {
      this.$toast.loading({
        message: '加载中',
        position: 'center',
        forbidClick: true,
        duration: 0
      });
      uploadImgByBase64({
        base64: this.imageBase64.replace('data:image/png;base64,', ''),
        business_id: this.$store.state.user.business_id
      }).then(result => {
        if (result && result.data) {
          let queryParams = this.$store.state.user.queryParams;
          let image = result.data.url;
          if (queryParams && queryParams.origin === 'toutiao') {
            this.showSaveImage = false;
            this.$toast.clear();
            tt.miniProgram.navigateTo({
              url: `/subPagesA/makePic/makePic?image=${image}&detail_id=${queryParams.id || ''}&tool_id=${queryParams.tool_id || ''}&seach_code=${queryParams.seach_code || ''}&isAuthor=${queryParams.isAuthor || 0}`,
              success(res) {
                console.log("跳转成功", res);
              },
              fail(err) {
                console.log("navigateTo调用失败", err);
              },
            });
          } else if (queryParams && queryParams.origin === 'kuaishou') {
            this.showSaveImage = false;
            this.$toast.clear();
            ks.navigateTo({
              url: `/subPagesA/makePic/makePic?image=${image}&detail_id=${queryParams.id || ''}&tool_id=${queryParams.tool_id || ''}&seach_code=${queryParams.seach_code || ''}&isAuthor=${queryParams.isAuthor || 0}`,
              success(res) {
                console.log("跳转成功", res);
              },
              fail(err) {
                console.log("navigateTo调用失败", err);
              },
            });
          } else if (queryParams && queryParams.origin === 'weixin') {
            this.showSaveImage = false;
            this.$toast.clear();
            wx.miniProgram.navigateTo({
              url: `/subPagesA/makePic/makePic?image=${image}&detail_id=${queryParams.id || ''}&tool_id=${queryParams.tool_id || ''}&seach_code=${queryParams.seach_code || ''}&isAuthor=${queryParams.isAuthor || 0}`,
              success(res) {
                console.log("跳转成功", res);
              },
              fail(err) {
                console.log("navigateTo调用失败", err);
              },
            });
          }
        }
      })
    },

    // 无水印制作
    handleMakePic() {
      this.$toast.loading({
        message: '加载中',
        position: 'center',
        forbidClick: true,
        duration: 0
      });
      let queryParams = this.$store.state.user.queryParams;
      let paramsObject = this.handAccountCanvas.getObject().toJSON([ 'isEdit', 'isMove', 'isMatting', 'elType', 'fontFamilySrc', 'selectable', '_index', 'crossOrigin', 'evented', 'colorType', 'opacity', 'xieYinColor', 'xieYinText', 'lockMovementX', 'lockMovementY', 'isSticker', 'textDirection', 'isXieyinImage' ]);
      createPicSynthesisLog({
        imageBase64: this.imageBase64,
        id: queryParams.id,
        tool_id: queryParams.tool_id,
        clips_param: paramsObject,
        title: this.title
      }).then(result => {
        if (result && result.data) {
          let image = result.data.url;
          let logId = result.data.id;
          if (queryParams && queryParams.origin === 'toutiao') {
            this.showSaveImage = false;
            this.$toast.clear();
            tt.miniProgram.navigateTo({
              url: `/subPagesA/makePic/makePic?image=${image}&detail_id=${queryParams.id || ''}&tool_id=${queryParams.tool_id || ''}&seach_code=${queryParams.seach_code || ''}&isAuthor=${queryParams.isAuthor || 0}&log_id=${logId}`,
              success(res) {
                console.log("跳转成功", res);
              },
              fail(err) {
                console.log("navigateTo调用失败", err);
              },
            });
          } else if (queryParams && queryParams.origin === 'kuaishou') {
            this.showSaveImage = false;
            this.$toast.clear();
            ks.navigateTo({
              url: `/subPagesA/makePic/makePic?image=${image}&detail_id=${queryParams.id || ''}&tool_id=${queryParams.tool_id || ''}&seach_code=${queryParams.seach_code || ''}&isAuthor=${queryParams.isAuthor || 0}&log_id=${logId}`,
              success(res) {
                console.log("跳转成功", res);
              },
              fail(err) {
                console.log("navigateTo调用失败", err);
              },
            });
          } else if (queryParams && queryParams.origin === 'weixin') {
            this.showSaveImage = false;
            this.$toast.clear();
            wx.miniProgram.navigateTo({
              url: `/subPagesA/makePic/makePic?image=${image}&detail_id=${queryParams.id || ''}&tool_id=${queryParams.tool_id || ''}&seach_code=${queryParams.seach_code || ''}&isAuthor=${queryParams.isAuthor || 0}&log_id=${logId}`,
              success(res) {
                console.log("跳转成功", res);
              },
              fail(err) {
                console.log("navigateTo调用失败", err);
              },
            });
          }
        }
      })
    },

    // 预览图片
    handleImagePreview() {
      let viewWc = this.handAccountCanvas.getViewWc();
      let handAccountCanvas = this.handAccountCanvas.getObject();
      let backgroundImageWidth = handAccountCanvas.backgroundImage.width * handAccountCanvas.backgroundImage.scaleX;
      let backgroundImageHeight = handAccountCanvas.backgroundImage.height * handAccountCanvas.backgroundImage.scaleY;
      const canvasContentEl = document.querySelector(`#canvasContentEl`); // 画布容器
      let multiplier = 3;
      let multiplier3 = parseFloat(backgroundImageWidth * viewWc * 3 || 0);
      if (multiplier3 < 750) {
        multiplier = 4;
      }

      let image = handAccountCanvas.toDataURL({
        width: backgroundImageWidth * viewWc,
        height: backgroundImageHeight * viewWc,
        left: ((canvasContentEl.offsetWidth - backgroundImageWidth * viewWc) / 2),
        top: ((canvasContentEl.offsetHeight - backgroundImageHeight * viewWc) / 2),
        multiplier: multiplier, // 导出的倍数
        quality: 1,
      });

      this.imageBase64 = image;
      let templateDetail = this.$store.state.design.templateDetail;
      this.templateDetail = templateDetail;
      this.title = templateDetail ? templateDetail.title : '';
      this.showSaveImage = true;
    },


    // 保存图片
    handleSave() {
      let viewWc = this.handAccountCanvas.getViewWc();
      let handAccountCanvas = this.handAccountCanvas.getObject();
      let backgroundImageWidth = handAccountCanvas.backgroundImage.width * handAccountCanvas.backgroundImage.scaleX;
      let backgroundImageHeight = handAccountCanvas.backgroundImage.height * handAccountCanvas.backgroundImage.scaleY;
      const canvasContentEl = document.querySelector(`#canvasContentEl`); // 画布容器

      let image = handAccountCanvas.toDataURL({
        width: backgroundImageWidth * viewWc,
        height: backgroundImageHeight * viewWc,
        left: ((canvasContentEl.offsetWidth - backgroundImageWidth * viewWc) / 2),
        top: ((canvasContentEl.offsetHeight - backgroundImageHeight * viewWc) / 2),
        multiplier: 3, // 导出的倍数
        quality: 1,
      });
      this.imageBase64 = image;
      let templateDetail = this.$store.state.design.templateDetail;
      this.templateDetail = templateDetail;
      this.title = templateDetail ? templateDetail.title : '';
      this.showImage = true;
    },

    // 保存成组
    handleSaveModel() {
      let paramsObject = this.handAccountCanvas.getObject().toJSON([ 'isEdit', 'isMove', 'isMatting', 'elType', 'fontFamilySrc', 'selectable', '_index', 'crossOrigin', 'evented', 'colorType', 'opacity', 'xieYinColor', 'xieYinText', 'lockMovementX', 'lockMovementY', 'isSticker', 'textDirection', 'isXieyinImage' ]);
      let viewWc = this.handAccountCanvas.getViewWc();
      let handAccountCanvas = this.handAccountCanvas.getObject();
      let backgroundImageWidth = handAccountCanvas.backgroundImage.width * handAccountCanvas.backgroundImage.scaleX;
      let backgroundImageHeight = handAccountCanvas.backgroundImage.height * handAccountCanvas.backgroundImage.scaleY;
      const canvasContentEl = document.querySelector(`#canvasContentEl`); // 画布容器

      let image = handAccountCanvas.toDataURL({
        width: backgroundImageWidth * viewWc,
        height: backgroundImageHeight * viewWc,
        left: ((canvasContentEl.offsetWidth - backgroundImageWidth * viewWc) / 2),
        top: ((canvasContentEl.offsetHeight - backgroundImageHeight * viewWc) / 2),
        multiplier: 3, // 导出的倍数
        quality: 1,
      });
      this.imageBase64 = image;
      let templateDetail = this.$store.state.design.templateDetail;
      this.templateDetail = templateDetail;
      this.title = templateDetail ? templateDetail.title : '';
      this.showImage = true;
      return {
        params: JSON.stringify(paramsObject),
        image,
      }
    },

    // 成组
    handleAddGroupModel() {
      let groupItem = this.handAccountCanvas.getObjects().filter(item => item.type === 'group');
      console.log(groupItem)
      if (groupItem && groupItem.length > 0) {
        let params = this.handleSaveModel();
        window.parent.postMessage({
          message: 'call-carmodel-params',
          arg: params
        }, '*'); // '*' 表示接受任何域的消息
        // console.log(params);
        // console.log(window.parent)
        // console.log(window.parent.listenEventCarModelParams(params))
      } else {
        this.handAccountCanvas.addGroup().then(result => {
          let params = this.handleSaveModel();
          window.parent.postMessage({
            message: 'call-carmodel-params',
            arg: params
          }, '*'); // '*' 表示接受任何域的消息
        });
      }
    },

    // 重置
    handleReloadModel() {
      location.reload();
    },

    // 保存图片2
    handleSave2() {
      let handAccountCanvas = this.handAccountCanvas.getObject();
      let image = handAccountCanvas.toDataURL({
        width: handAccountCanvas.width,
        height: handAccountCanvas.height,
        multiplier: 2 // 导出的倍数
      });
      // ImagePreview([ image ]);
      this.imageBase64 = image;
      let templateDetail = this.$store.state.design.templateDetail;
      this.templateDetail = templateDetail;
      this.title = templateDetail ? templateDetail.title : '';
      this.showImage = true;
    },

    // 提交
    sumbitImage() {
      this.$toast.loading({
        message: '上传中',
        position: 'center',
        forbidClick: true,
        duration: 0
      });
      uploadImgByBase64({
        base64: this.imageBase64.replace('data:image/png;base64,', ''),
        business_id: this.$store.state.user.business_id
      }).then(result => {
        if (result && result.data) {
          let queryParams = this.$store.state.user.queryParams;
          let paramsObject = this.handAccountCanvas.getObject().toJSON([ 'isEdit', 'isMove', 'isMatting', 'elType', 'fontFamilySrc', 'selectable', '_index', 'crossOrigin', 'evented', 'colorType', 'opacity', 'xieYinColor', 'xieYinText', 'lockMovementX', 'lockMovementY', 'isSticker', 'textDirection', 'isXieyinImage' ]);
          paramsObject.clipPath.width = paramsObject.backgroundImage.width * paramsObject.backgroundImage.scaleX;
          paramsObject.clipPath.height = paramsObject.backgroundImage.height * paramsObject.backgroundImage.scaleY;
          let currentElement = this.handAccountCanvas.getObject();
          paramsObject.width = currentElement.width;
          paramsObject.height = currentElement.height;
          let params = {
            id: queryParams.id || '',
            tool_id: queryParams.tool_id,
            params: paramsObject,
            cover_url: `${result.data.wx_cover_url || result.data.url}`,
            thumbnail: `${result.data.url}`,
            wallpaper_bg: '',
            business_id: queryParams.business_id,
            title: this.title,
          }
          createWallpaperTemplate(params).then(result => {
            this.$toast.clear();
            if (result && result.code === 200) {
              this.$toast({
                message: '提交成功',
                position: 'center',
              });
              // location.reload();
            }
          })
        }
      })
    },

    // 苹果保存提示
    handleIosTip() {
      this.$toast({
        message: '由于相关政策原因，苹果系统暂时不支持',
        position: 'center',
      });
    },

    // 撤销
    prevStepOperate() {
      this.handAccountCanvas.prevStepOperate();
    },

    // 还原
    nextStepOperate() {
      this.handAccountCanvas.nextStepOperate();
    },

    // 显示图层
    handlelayer() {
      if (this.currentSelectionElement) {
        this.layerShow = !this.layerShow;
        this.moreShow = false;
      } else {
        this.$toast({
          message: '请选择要编辑的元素',
          position: 'center'
        });
      }
    },

    // 置顶
    itemBringToFront() {
      this.handAccountCanvas.itemBringToFront();
    },

    // 置底
    itemSendToBack() {
      this.handAccountCanvas.itemSendToBack();
    },

    // 上一层
    itemBringForward() {
      this.handAccountCanvas.itemBringForward();
    },

    // 下一层
    itemSendBackwards() {
      this.handAccountCanvas.itemSendBackwards();
    },

    // 点击更多
    hanleMore() {
      if (this.currentSelectionElement) {
        this.moreShow = !this.moreShow;
        this.layerShow = false;
      } else {
        this.$toast({
          message: '请选择要编辑的元素',
          position: 'center'
        });
      }
    },

    // 点击是否锁定
    handleEdit() {
      let currentSelectionElement = this.currentSelectionElement;
      this.handAccountCanvas.updatedItem('edit', !currentSelectionElement.isEdit);
    },

    // 点击是否为谐音底图
    handleXieyinImage() {
      let currentSelectionElement = this.currentSelectionElement;
      this.handAccountCanvas.updatedItem('xieyinImage', currentSelectionElement.isXieyinImage ? currentSelectionElement.isXieyinImage : true);
    },

    // 点击是否锁定
    handleSticker() {
      let currentSelectionElement = this.currentSelectionElement;
      this.handAccountCanvas.updatedItem('sticker', !currentSelectionElement.isSticker);
    },

    // 点击是否可移动
    handleMove() {
      let currentSelectionElement = this.currentSelectionElement;
      this.handAccountCanvas.updatedItem('move', !currentSelectionElement.isMove);
    },

    // 点击锁定
    handleSelectable() {
      let currentSelectionElement = this.currentSelectionElement;
      this.handAccountCanvas.updatedItem('selectable', !currentSelectionElement.selectable);
    },

    // 点击抠图
    handleMatting() {
      let currentSelectionElement = this.currentSelectionElement;
      if (currentSelectionElement.type !== 'image') {
        this.$toast({
          message: '非图片元素，不可以使用',
          position: 'center'
        });
        return;
      }
      this.handAccountCanvas.updatedItem('matting', !currentSelectionElement.isMatting);
    },

    // 设置为背景底图
    handleSetBackgroundImage() {
      this.handAccountCanvas.setBackgroundImage();
    },
    
  }
}
</script>

<style lang="less" scoped>
  @mainColor: #AAB9E3;

  .image-container{
    padding: 12px 24px;
  }

  .image-content{
    max-height: 420px;
    overflow-y: auto;
    overflow-x: hidden;
  }

  .footer-content{
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 46px;

    .item{
      text-align: center;
      position: relative;
      min-width: 60px;
    }

    .save-btn-container{
      flex: 1;
      display: flex;
      margin-left: 140px;
      margin-right: 16px;
      justify-content: flex-end;

      .save-text{
        font-size: 13px;
      }
    }

    .ios-btn-tip{
      margin-left: 100px;
    }

    .layer-container{
      position: absolute;
      left: -74px;
      right: 0;
      margin: auto;
      width: 188px;
      z-index: 9999;
      padding: 6px;

      .layer-content{
        width: 100%;
        // background-color: #fff;
        display: flex;
        border-radius: 4px;
        box-shadow: 0rpx 8rpx 10rpx 2rpx #EEEEF3;
        display: flex;
        align-items: center;
        padding: 14px 5px 8px 5px;
        overflow: hidden;
        // background: url(https://diy.eu14.cn/2023/09/27/20230927094313-pic_tc_fl.webp);
        background: url(https://diy.eu14.cn/2023/09/27/20230927094313-pic_tc_fl.webp);
        background-size: 100% 100%;
        flex-wrap: wrap;
      }

      .layer-item{
        color: #8773f9;
        min-width: 46px;
        margin-bottom: 6px;

        .layer-item-icon{
          width: 16px;
          height: 16px;
          border: 0;
          display: block;
          margin: auto;
        }
      }

      .item-label-text{
        font-size: 10px;
      }
      
    }

    .item-label{
      font-size: 10px;
      color: #fff;
    }

    .item-icon{
      width: 20px;
      height: 20px;
      border: 0;
      display: block;
      margin: auto;
    }

    .save-btn{
      width: 48px;
      height: 24px;
      font-size: 14px;
      color: @mainColor;
      font-weight: bold;
      line-height: 24px;
      text-align: center;
      border-radius: 15px;
      background: #fff;
      border: 1px solid #fff;
    }

    .preview-title{
      font-size: 16px;
      font-weight: bold;
      text-align: center;
      padding: 12px 0 24px 0;
    }

    .save-tip{
      color: #888;
      font-size: 12px;
      padding: 24px 0;
    }

    .preview-image-container{
      overflow: hidden;
      position: relative;

      .water-container{
        width: 100%;
        height: 100%;
        background: url(https://baiwan-product.oss-cn-hangzhou.aliyuncs.com/watermark/desingshuiying.png);
        background-size: cover;
        position: absolute;
        pointer-events: none;
      }
    }

    .preview-btn-container{
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;
    }
  }
  .set-direction{
    display: flex;
    padding: 10px 16px;
    .label{
      width: 4em;
      margin-right: 12px;
    }
  }
</style>
